<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>添加付款管理</title>
	<link rel="stylesheet" href="../css/from.css">
	<link rel="stylesheet" href="../themes/default/easyui.css">
	<link rel="stylesheet" href="../themes/icon.css">
	<script src="../js/jquery.min.js"></script>
	<script src="../js/jquery.easyui.min.js"></script>
	<script src="../js/easyui-lang-zh_CN.js"></script>
	<script>
        var company=null;
        //关闭当前这个页面
        function closeTab(){
            parent.tabsClose();
        }

        //支付方法
        function payCurrentPayBill(){
            $.messager.confirm('确认','您确认想要支付吗？',function(r){
                if (r){
                    $("#addDate").datebox('setValue','yyyy-mm-dd');
                    if ($("#savePayBill_btn").attr('title')=="save"){
                        $.ajax({
                            url: "../../payBillController/payCurrentPayBill",
                            data: {code:$("#code").val()},
                            dataType:"text",
                            success:function(data){
                                alert(data);
                            }
                        });
                        $.ajax({
                            url: "../../payBillController/findPayBill",
                            data:{payCode:$("#code").val()}
                        });
                        window.location.href="paybill_detail_checked.html";
					} else{
                        if(savePayBillDetailToDataBase()){
                            $.ajax({
                                url: "../../payBillController/payCurrentPayBill",
                                data: {code:$("#code").val()},
                                beforeSend:function(){
                                    return true;
                                },
                                dataType:"text",
                                success:function(data){
                                    alert(data);
                                    $.ajax({
                                        url: "../../payBillController/findPayBill",
                                        data:{payCode:$("#code").val()}
                                    });
                                    window.location.href="paybill_detail_checked.html";
                                }
                            });
                        }else{
                            alert("保存时失败！");
                        }
					}
                }
            });

        }

        //保存方法
        function savePayBillDetailToDataBase(){
            if (!$("#addDate").datebox('isValid')){
                alert("请输入正确的时间");
                return false;
            }else if (!$("#supplierName").textbox('isValid')){
                alert("请填写供应商")
			} else{
                //生成paybill的ajax
                $('#form1').form('submit', {
                    url: "../../payBillController/addPayBill",
                    success:function(data){
                        //保存paybilldetail的ajax
                        var rows=$("#productList").datagrid("getRows");
                        if (rows.length!=0){
                            $.ajax({
                                url: "../../payBillController/savePayBillDetailToDataBase",
                                data: {saveRows: JSON.stringify(rows),
                                    payCode: $("#code").val(),
                                    payData: $("#addDate").datebox("getText"),
                                    payType: $("#contacter").combobox("getValue"),
                                    payTotalMoney: $("#type").textbox('getText'),
                                    memo: $("#fax").textbox("getText")},
                                dataType: "text",
                                /*success: function(data){
                                    if(data=="success"){
                                        alert("保存成功");
                                    }
                                },*/
                                error: function(){
                                    return false;
                                }
                            });
                        } else{
                            alert("没有需要保存的入库单")
                        }

                    }
                });
                alert("保存成功！");
                $("#savePayBill_btn").attr("disabled", true);
                $("#savePayBill_btn").attr("title", "save");
                return true;
            }
        }

        //删除instroagebill的一行数据，删除后重置datagrid
        function deleteInstroageBillInRow(index){
            var rows=$("#productList").datagrid('getRows');
            var a=parseFloat($("#type").textbox('getValue'));
            var b=rows[index].money;
            var curMoney=a-b;
            $("#type").textbox('setValue',curMoney);
            $("#productList").datagrid('deleteRow',index);
            rows=$("#productList").datagrid('getRows');
            $("#productList").datagrid('loadData',rows);
        }

        //从未选择的introagebill选择一个添加
        function addInstroageBillTopaybill(){
            var selectRows=$("#instroagebill").datagrid("getSelections");
            var rows=$("#productList").datagrid("getRows");
            if(selectRows==null||selectRows==""){
                alert("请选择入库单！");
                return false;
            }
            var flag=false;
            if(rows!=null||rows!=""){
                for(var i=0;i<selectRows.length;i++){
                    for(var j=0;j<rows.length;j++){
                        if(rows[j].code==selectRows[i].code){
                            flag=true;
                        }
                    }
                }
                if(flag==false){
                    for(var i=0;i<selectRows.length;i++){
                        $("#productList").datagrid('appendRow',selectRows[i]);
                        var curMoney=parseFloat($("#type").textbox('getValue'))+selectRows[i].money;
                        $("#type").textbox('setValue',curMoney);
                    }
                }else{
                    alert("请不要选择重复入库单！");
                    $("#instroagebill").datagrid("clearSelections");
                    $("#instroagebill").datagrid("clearChecked");
                    return false;
                }
            }else{
                for(var i=0;i<selectRows.length;i++){
                    $("#productList").datagrid('appendRow',selectRows[i]);
                    var curMoney=parseFloat($("#type").textbox('getValue'))+selectRows[i].money;
                    $("#type").textbox('setValue',curMoney);
                }
            }
            $("#win").window('close');
        }

        //加载paybill的入库单
        function searchInstroageBill(){
            var json = {
                findcode: $("#findcode_I").val(),
                findstartDate: $("#findstartDate_I").val(),
                findendDate: $("#findendDate_I").val(),
                findsupplierName: $("#findsupplierName_I").val()
            };
            loadInstroageListByPayBill(json);

        }

        //重置instroagebill面板的查找表单
        function resetForm(){
            $("#form3").form('reset');
            $("#form3").form('load',{
                findsupplierName_I: $("#supplierName").val()
            });
        }

        //加载paybill的instroagebill 的datagrid方法
        function loadInstroageListByPayBill(params){
            $("#instroagebill").datagrid({
                fit: true,
                url:'../../payBillController/loadUnselectedInstroageBill',
                toolbar:'#instroageToolbar',
                rownumbers:true,
                checkOnSelect:true,
                columns:[[
                    {field: "ck",checkbox:true},
                    {field:'code',title:'入库单号'},
                    {field: "customName",title: "供应商名"},
                    {field: "instroageDate",title: "入库日期",formatter: function (value,row,index) {
                            var date=new Date(value).toLocaleDateString().replace(/\//g,'-');
                            return date;
                        }},
                    {field:'money',title:'应付金额'},
                    {field:'payStatus',title:'实付金额',formatter:function(value,row,index){
                            if(value==1){
                                return "0.00";
                            }else if(value==2){
                                return row.money;
                            }
                        }},
                    {field:'memo',title:'备注'}
                ]],
                pagination: true,//向后台传递参数page 和rows
                pageNumber: 1,
                pageSize: 5,
                pageList: [5,10,20],
                queryParams: params

            });
        }

        //关闭instroagebill面板
        function closeInstroageField(){
            $("#win").window('close');
        }

        //从面板添加一个未选择的instroagebill到paybill的instroagebill
        function addNewInstroageBill(){
            if ($("#supplierName").val()==null || $("#supplierName").val()==''){
                alert("请选择供应商！");
                loadSupplier();
			} else{
                $("#win").window('open');
                $("#form3").form('load',{
                    findsupplierName_I: $("#supplierName").val()
                });
                $("#findsupplierName_I").textbox({readonly: true});
                loadInstroageListByPayBill({findsupplierName: $("#supplierName").val()});
			}
        }

        function loadDataGrid_company(params){
            $("#dataGrid_company").datagrid({
                fit:true,
                url:'../../payBillController/companyPayBill',
                rownumbers:true,
                checkOnSelect:false,
                columns:[[
                    {field:'code',title:'供应商代号'},
                    {field:'name',title:'供应商名称'},
                    {field:'type',title:'类型',formatter:function(value){
                            if(value==1){
                                return "客户";
                            }else if(value==2){
                                return "供应商";
                            }
                        }},
                    {field:'linkman',title:'联系人'},
                    {field: "phone",title: "电话"},
                    {field: "fax",title: "传真"},
                    {field: "address",title: "地址"}
                ]],
                toolbar:'#searchdiv',
                queryParams: params,
                pagination:true ,//向后台传递参数page 和rows
                pageNumber: 1,
                pageSize: 5,
                pageList: [5,10,20],
                onDblClickRow: function(index, row){
                    company=row.name;
                    $('#win1').window('close');
                    $("#form2").form("reset");
                    $("#supplierName").textbox({value:company});
                    var datagrid_length=$("#productList").datagrid('getRows').length;
                    for (var i=0;i<datagrid_length;i++){
                        deleteInstroageBillInRow(0);
					}

                }
            });
		}

        function searchCompany(){
            var params={"name":$("#findcode1").val(),"code":$("#findendDate1").val(),"type":$("#companyType").val()};
            loadDataGrid_company(params);
        }
        function loadSupplier() {
            loadDataGrid_company(null);
            $('#win1').window('open');
        }


        $(function(){
            /*设置日期验证器*/
            $.extend($.fn.validatebox.defaults.rules, {
                end: {
                    validator: function (value, param) {
                        var curDate=new Date();
                        var startTmp=new Date(curDate.toLocaleDateString());
                        var endTmp = new Date(value.replace(/-/g, "/"));
                        return startTmp <= endTmp;
                    },
                    message: '日期不能选择当前日期（今日）之前'
                }
            });
            /*初始化已选择入库表格*/
            /* 初始化数据表格 */
            $("#productList").datagrid({
                fit:true,
                /* rownumbers:true, */
                checkOnSelect:false,
                singleSelect: true,
                rownumbers: true,
                toolbar: '#form_field',
                columns:[[
                    {field:'code',title:'业务单号',width: 122},
                    {field: "customName",title: "供应商名",editor: "text",width: 180},
                    {field:'money',title:'应付金额',width: 80},
                    {field:'payStatus',title:'实付金额',width: 80,formatter:function(value,row,index){
                            if(value==1){
                                return "0.00";
                            }else if(value==2){
                                return row.money;
                            }
                        }},
                    {field:'memo',title:'备注'},
                    {field: "operation",title: "操作",width: 100,formatter:function(value,row,index){
                            return "<a id='a_id_"+index+"' href='#' onclick='deleteInstroageBillInRow("+index+")'>删除</a>";
                        }}
                ]],
                pagination:true ,//向后台传递参数page 和rows
                pageNumber: 1,
                pageSize: 5,
                pageList: [5,10,20]/* ,
        onClickRow: function(index, row){
        	$("#productList").datagrid('beginEdit',index);
            } */
            });

            /*供应商弹窗设置*/
            $('#win1').window({
                width:800,
                height:400,
                modal:true,
                title:"请选择 供应商 温馨提示：双击选择供应商",
                onBeforeClose:function(){
                    $("#form2").form("reset");
                    return true;
                }
            });

            $('#win1').window('close');
            $('#form1').form('load','../../payBillController/beforeAddPayBill');
            $("#code").textbox('readonly',true);
            $("#code").textbox('textbox').css('background','#CCCCCC');
            $("#supplierName").textbox('readonly',true);
            $("#type").textbox('readonly',true);
            $("#type").textbox('setValue',0.00);
            $("#contacter").combobox({editable:false});
			/*入库单弹窗设置*/
            $("#win").window({
                onResize: function(width, height){
                    $("#instroageField").height(($("#win").height()-30));
                },
                onBeforeOpen:function(){
                    $("#instroageField").height(($("#win").height()-30));
                },
                onBeforeOpen:function(){
                    $("#form3").form('reset');
                    loadInstroageListByPayBill(null);
                }
            });
            $("#win").window('close');
            /* 入库单弹窗textbox */
            $("#findcode_I").textbox({
                width: '100px'
            });
            $("#findsupplierName_I").textbox({
                width: '200px'
            });
            $("#findstartDate_I").datebox({
                width: '120px'
            });
            $("#findendDate_I").datebox({
                width: '120px'
            });
		});
       

	</script>
	<style>
		body {
			font-size: 12px;
			padding: 10px
		}

		.l-table-edit {
			border: #84a0c4 1px solid
		}

		.l-table-edit-td {
			padding: 4px;
			font-size: 12px;
		}
	</style>


</head>
<body>
<div id="form_field" style="background-color: white;">
	<form name="form1" id="form1" action="" method="post">
		<table cellpadding="0" cellspacing="0" class="l-table-edit"
			   style="width: 100%">
			<tr>
				<td width="17%" align="right" class="l-table-edit-td">付款单号：</td>
				<td width="27%" align="left" class="l-table-edit-td"><input
						class="easyui-textbox" name="code" type="text" id="code" size="30"
						maxlength="100" ltype="text" /></td>
				<td width="13%" align="right" class="l-table-edit-td">付款日期：</td>
				<td width="43%" align="left" class="l-table-edit-td"><input
						class="easyui-datebox" type="text" id="addDate" data-options="required:true,validType:['end']" name="payDate"/></td>
			</tr>
			<tr>
				<td width="17%" align="right" class="l-table-edit-td"><a
						href="#" onclick="loadSupplier()">供应商：</a></td>
				<td align="left" class="l-table-edit-td"><input
						class="easyui-textbox" type="text" id="supplierName" value=""
						size="30" maxlength="100" ltype="text" name="customName" data-options="required:true"/>
				<td width="13%" align="right" class="l-table-edit-td">付款方式：</td>
				<td align="left" class="l-table-edit-td"><select
						class="easyui-combobox" name="payType" id="contacter" style="width: 160px">
					<option value="1">现金</option>
					<option value="2">转账</option>
				</select></td>
			</tr>
			<tr>
				<td width="17%" align="right" class="l-table-edit-td">付款金额：</td>
				<td align="left" class="l-table-edit-td"><input
						class="easyui-textbox" type="text" id="type" value="" size="30"
						maxlength="50" ltype="text" name="payTotalMoney"/></td>
				<td width="17%" align="right" class="l-table-edit-td">备注：</td>
				<td align="left" class="l-table-edit-td"><input type="text"
																class="easyui-textbox" id="fax" value="" maxlength="50"
																ltype="text" name="memo"/></td>
			</tr>

		</table>
	</form>
	<br>
	<input type="button" value="选入库单" style="cursor:pointer;width: 60px"
		   onclick="addNewInstroageBill()">
	<input id="savePayBill_btn" type="button" value="保      存" style="cursor:pointer;width: 60px" onclick="savePayBillDetailToDataBase()">&ensp;
	<input type="button" value="付      款" style="cursor:pointer;width: 60px" onclick="payCurrentPayBill()">&ensp;
	<input type="button" value="撤      销" style="cursor:pointer;width: 60px" disabled="disabled">&ensp;
	<input type="button" value="关     闭" style="cursor:pointer;width: 60px" onclick="closeTab()">&ensp;
	<div style="display: block; height: 14px"></div>
</div>
<div id="productList" class="easyui-datagrid"></div>
<div id="win1">
	<div id="dataGrid_company" class="easyui-datagrid">
		<div id="searchdiv" style="display: block; width: 100%;">
			<form name="form2" id="form2">
				<table width="100%" border="0" cellspacing="0"
					   style="background-color: #c9dfff;">
					<tbody>
					<tr>
						<td width="70"><b>检索条件:</b></td>
						<td width="70" align="right">单位名称:</td>
						<td width="150" align="left"><input name="findcode"
															type="text" id="findcode1" maxlength="100"></td>
						<td width="70" align="right">单位代号:</td>
						<td width="150" align="left"><div class="l-text-wrapper">
							<div class="l-text l-text-date">
								<input name="findendDate" type="text" id="findendDate1"
									   value="" maxlength="30" ligeruiid="findendDate">
							</div>
						</div></td>
						<td width="70" align="right">单位类别:</td>
						<td width="150" align="left">
							<select id="companyType">
								<option value="">请选择</option>
								<option value="1">客户</option>
								<option value="2">供应商</option>
							</select>
						</td>
						<td width="72"><a id="search_btn" href="#"
										  class="easyui-linkbutton" data-options="iconCls:'icon-search'" onclick="searchCompany()">搜索</a>
						</td>
					</tr>
					</tbody>
				</table>
				<input type="hidden" id="menuCode" value="100001001">
			</form>
		</div>
	</div>
</div>
<div id="win" class="easyui-window easyui-layout" title="请选择 入库单"
	 style="width: 990px; height: 330px"
	 data-options="iconCls:'icon-save',modal:true">

	<div id="instroageField">
		<div id="instroageToolbar">
			<form name="form3" id="form3">
				<table width="100%" border="0" cellspacing="0"
					   style="background-color: #c9dfff;">
					<tbody>
					<tr>
						<td width="70"><b>检索条件:</b></td>
						<td width="70" align="right">入库单号:</td>
						<td width="110" align="left"><input name="findcode"
															class="easyui-textbox" type="text" id="findcode_I"></td>
						<td width="70" align="right">开始日期:</td>
						<td width="110" align="left"><input name="findstartDate"
															type="text" id="findstartDate_I" class="easyui-datebox"></td>
						<td width="70" align="right">结束日期:</td>
						<td width="110" align="left"><input name="findendDate"
															type="text" id="findendDate_I" class="easyui-datebox"></td>
						<td width="70" align="right">供应商名:</td>
						<td width="110" align="left"><input
								name="findsupplierName_I" class="easyui-textbox" type="text"
								id="findsupplierName_I"></td>
						<td width="72"><a id="search_btn_I" href="#"
										  class="easyui-linkbutton" data-options="iconCls:'icon-search'"
										  onclick="searchInstroageBill()">搜索</a></td>
						<td width="72"><a id="reset_btn" href="#"
										  class="easyui-linkbutton" data-options="iconCls:'icon-refresh'"
										  onclick="resetForm()">重置</a></td>
						<td width="0"></td>
					</tr>
					</tbody>
				</table>
			</form>
		</div>
		<div id="instroagebill" class="easyui-datagrid"></div>
	</div>
	<div id="instroagebill_btn" class=""
		 style="height: 30px; width: 100%; display: table; line-height: 30px;">
		<div style="float: right; line-height: 30px;">
			<input type="button" value="退出"
				   style="float: right; display: inline-block; vertical-align: middle; margin: 4px;cursor:pointer;"
				   onclick="closeInstroageField()">&ensp;&ensp; <input
				type="button" value="添加入库单"
				style="float: right; display: inline-block; vertical-align: middle; margin: 4px;cursor:pointer;"
				onclick="addInstroageBillTopaybill()">&ensp;&ensp;
		</div>
	</div>
</div>
</body>
</html>